package middleware

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"jsjb/tools/jwt"
	"net/http"
)

func ParseAuth() gin.HandlerFunc {
	return func(c *gin.Context) {
		token, msg := getToken(c)
		fmt.Printf("token=>%v,msg=>%v\n", token, msg)
		if token == "" {
			c.JSON(http.StatusOK, gin.H{
				"msg":  msg,
				"code": 20002,
			})
			c.Abort()
			return
		}
		claims, err := jwt.ParseToken(token)
		if err != nil {
			c.JSON(http.StatusOK, gin.H{
				"msg":  err,
				"code": 20001,
			})
			c.Abort()
			return
		}
		fmt.Printf("%+v\n", claims)
		c.Set("userInfo", claims.User)
		c.Next()
	}
}

func getToken(c *gin.Context) (token, msg string) {
	headers := c.Request.Header
	if headers["Authorization"] == nil {
		msg = "缺少Authorization"
	} else {
		auth := headers["Authorization"]
		if auth[0] == "" {
			msg = "Authorization格式有误"
			return
		}
		if a := auth[0]; a[6:] == "" {
			msg = "Authorization格式有误"
		} else {
			msg = "success"
			token = a[7:]

		}
	}

	return
}
